
/*
 * 支付
 *
 * @param {String} payment = ['wechat','wx','alipay','wallet','offline']  	- 支付方式
 * @param {String} orderType = ['goods',goods_n','recharge','groupon']  	- 订单类型
 * @param {String} orderSN					- 订单号
 */
import request from '@/utils/request.js'
export default class SheepPay {
	constructor(payment, orderType, orderSN,type) {
		this.type = type?type:null
		this.payment = payment;
		if(orderType=='addressChange'){
			this.params = orderSN
		}else{
			if(!isNaN(orderSN) && !isNaN(parseFloat(orderSN))){
				this.order_id = orderSN;
				this.order_no = '';
			}else{
				this.order_id = '';
				this.order_no = orderSN;
			}
		}		
		console.log(orderType,"orderType")
		this.orderType = orderType; 
		
-		this.payAction();
	}

	payAction() {
		const payAction = {
			
			WechatMiniProgram: {
				wx: () => {
					console.log("go this ")
					this.wxPay();
				},
				wechat: () => {
					this.wechatMiniProgramPay();
				},
				alipay: () => {
					this.copyPayLink();
				},
				money: () => {
					this.moneyPay();
				},
				offline: () => {
					this.offlinePay();
				}
			},
			App: {
				wx: () => {
					this.wxPay();
				},
				wechat: () => {
					this.wechatAppPay();
				},
				alipay: () => {
					this.alipay();
				},
				money: () => {
					this.moneyPay();
				},
				offline: () => {
					this.offlinePay();
				}
			},
			H5: {
				wx: () => {
					this.wxPay();
				},
				wechat: () => {
					this.wechatWapPay();
				},
				alipay: () => {
					this.redirectPay();
				},
				money: () => {
					this.moneyPay();
				},
				offline: () => {
					this.offlinePay();
				}
			},
		};
		//#ifdef H5
		var platform='H5'
		//#endif
		//#ifdef MP-WEIXIN
		var platform='WechatMiniProgram'
		//#endif
		//#ifdef APP-PLUS
		var platform='App'
		//#endif
		return payAction[platform][this.payment]();
	}

	//预支付
	prepay() {
		return new Promise((resolve, reject) => {
			//#ifdef H5
			var platform='h5'
			//#endif
			//#ifdef MP-WEIXIN
			var platform='wechat'
			//#endif
			//#ifdef APP-PLUS
			var platform='app'
			//#endif
			
			if(this.orderType == 'activity' || this.orderType == 'activity2'){
				let data = {
					// order_no: this.order_no,
					id:this.order_id,
					pay_channel:this.payment,
					platform:platform,
					type:this.type
				};
				// #ifdef MP-WEIXIN
				console.log(uni.getStorageSync('openid'),"openid")
				if (uni.getStorageSync('openid')) {
					data.openid = uni.getStorageSync('openid');
				}
				// #endif
				var url
				if(this.orderType == 'activity'){
					url="User_Activity/getPayment";
				}else{
					url="User_Activity/getPayment2";
				}
				
				console.log(data,"data")
				request.getData(url,data).then(res=>{
					res.code === 1 && resolve(res);
					if (res.data === 0) {
						uni.showToast({
							title: res.msg,
							success: function (res) {},
						});
					}
				}).catch(err=>{
					console.log(err,"err")
				});
			}else{
				
				let data = {
					order_no: this.order_no,
					order_id:this.order_id,
					pay_type:this.payment,
					platform:platform
				};
				// #ifdef MP-WEIXIN
				if (uni.getStorageSync('openid')) {
					data.openid = uni.getStorageSync('openid');
				}
				// #endif
				var url='order/repay';
				if(this.orderType == 'address'){
					url='order/payAddress';
				}
				if(this.orderType == 'addressChange'){
					url='order/pay';
					data = this.params
					data.pay_type = this.payment
					data.platform = platform
				}
				request.getData(url,data).then(res=>{
					res.code === 1 && resolve(res);
					if (res.data === 0) {
						uni.showToast({
							title: res.msg,
							success: function (res) {},
						});
					}
				});
			}
		

		});
	}
	

	//浏览器微信H5支付
	async wechatWapPay() {
		const {
			code,
			data
		} = await this.prepay();
		if (code === 1) {
			const redirect_url = `${this.getRootUrl()}pages/pay/result?orderSN=${this.orderSN}&payment=${this.payment
				}&orderType=${this.orderType}`;
			location.href = `${data.pay_info.h5_url}&redirect_url=${encodeURIComponent(redirect_url)}`;
		}
	}


	//支付链接
	async redirectPay() {
		let {
			code,
			data
		} = await this.prepay();
		if (code === 1) {
			// const redirect_url = `${this.getRootUrl()}pages/pay/result?orderSN=${this.orderSN}&payment=${this.payment
			// 	}&orderType=${this.orderType}`;
			console.log(data.pay_info.data)
			document.querySelector('body').innerHTML = data.pay_info.data
			console.log(document)
			document.forms[0].submit()
			//return
			//location.href = data.pay_info + encodeURIComponent(redirect_url);
		}
	}
	
	
	wxPay() {
		
		var that=this
		that.prepay().then((res) =>{
			  var code=res.code
			  var data=res.data
			  var order_sn=res.busiMerNo
			  if (code === 1) {
				  
				uni.showModal({
				    title: '支付提示',
				    content: '请在好收银小程序内完成支付',
					confirmText: '支付成功',  //设置确认按钮文字
					cancelText: '取消支付',   //设置取消按钮文字
				    success: function (ress) {
				        if (ress.confirm) {
							that.payResult('success');
				            //console.log('用户点击确定');
				            //用户点击了确定按钮的相关逻辑可以放在这里
				        } else if (ress.cancel) {
				            console.log('用户点击取消');
				            //用户点击了取消按钮的相关逻辑可以放在这里
				        }
				    }
				});  
				wx.navigateToMiniProgram({
					appId: data.pay_info.chnlUrl,
					path: data.pay_info.path, 
					fail: e => {
					  console.log(e)
					}
				  })
			  }
		})
		//if(!uni.getStorageSync('openid')){
		//	console.log("21122")
		//	wx.login({
		//	  success: function(res) {
		//			if (res.code) {
		//			  sheep.$api.third.get_openid({'code':res.code}).then((res) =>{
		//				  uni.setStorageSync('openid',res.data.openid)
		//				  console.log("openid",res.data.openid)
		//				  that.prepay().then((res) =>{
		//					  var code=res.code
		//					  var data=res.data
		//					  if (code === 1) {
		//					  	//uni.navigateTo({
		//					  	//  url: "/pages/public/webview?url="+encodeURIComponent(data.pay_info.chnlUrl)//跳转到对应路径的页面
		//					  	//});
		//						wx.navigateToMiniProgram({
		//							appId: data.pay_info.chnlUrl,
		//							path: data.pay_info.path, 
		//							fail: e => {
		//							  console.log(e)
		//							}
		//						  })
							  	
		//					  }
		//				  })
		//			  })
		//			}
		//		}
		//	});
			
		//}else{
		//	console.log("31122")
		//	that.prepay().then((res) =>{
		//		  var code=res.code
		//		  var data=res.data
		//		  if (code === 1) {
		//			wx.navigateToMiniProgram({
		//				appId: data.pay_info.chnlUrl,
		//				path: data.pay_info.path, 
		//				fail: e => {
		//				  console.log(e)
		//				}
		//			  })
		//		  }
		//	})
		//}
		
	}
	
	//微信小程序支付
	async wechatMiniProgramPay() {
		let that = this;
		let result = await this.prepay();
		uni.requestPayment({
			provider: 'wxpay',
			...result.data.pay_info,
			success: (res) => {
				that.payResult('success');
			},
			fail: (err) => {
				if (err.errMsg === 'requestPayment:fail cancel') {
					uni.showToast({
						title: '支付已手动取消',
						icon: 'none',
						duration: 2000
					});
				} else {
					that.payResult('fail');
				}
			},
		});
	}

	//余额支付
	async moneyPay() {
		const {
			code
		} = await this.prepay();
		code === 1 && this.payResult('success');
	}

	//货到付款
	async offlinePay() {
		const {
			code
		} = await this.prepay();
		code === 1 && this.payResult('success');
	}

	//支付宝复制链接支付
	async copyPayLink() {
		let that = this;
		let {
			code,
			data
		} = await this.prepay();
		if (code === 1) {
			//引入showModal 点击确认 复制链接；
			uni.showModal({
				title: '支付宝支付',
				content: '复制链接到外部浏览器',
				confirmText: '复制链接',
				success: (res) => {
					if (res.confirm) {						
						uni.setClipboardData({
						    data: data.pay_info,
						    success: function () {
						        uni.showToast({
						            title: '复制成功',
						            icon: 'success',
						            duration: 2000
						        });
						    },
						    fail: function (err) {
						        console.error('复制失败: ', err);
						    }
						});
					}
				},
			});
		}
	}

	//支付宝支付
	async alipay() {
		let that = this;
		const {
			code,
			data
		} = await this.prepay();
		// const {
		// 	code,
		// 	data
		// } = await request.getData('demo/test')
		if (code === 1) {
			console.log(data.pay_info.data)
			uni.requestPayment({
				provider: 'alipay',
				orderInfo: data.pay_info.data, //支付宝订单数据
				success: (res) => {
					console.log(res)
					that.payResult('success');
				},
				fail: (err) => {
					console.log(err)
					if (err.errMsg === 'requestPayment:fail [paymentAlipay:62001]user cancel') {
						
						uni.showToast({
							title: '支付已手动取消',
							icon: 'none',
							duration: 2000
						});
					} else {
						that.payResult('fail');
					}
				},
			});
		}
	}

	//微信支付
	async wechatAppPay() {
		let that = this;
		let {
			code,
			data
		} = await this.prepay();
		if (code === 1) {
			uni.requestPayment({
				provider: 'wxpay',
				orderInfo: data.pay_info, //微信订单数据(官方说是string。实测为object)
				success: (res) => {
					that.payResult('success');
				},
				fail: (err) => {
					err.errMsg !== 'requestPayment:fail cancel' && that.payResult('fail');
				},
			});
		}
	}

	//支付结果跳转,success:成功，fail:失败
	payResult(resultType) {
		if(resultType=='success'){
			if(this.orderType == 'activity'){
				uni.redirectTo({
					url: '/subpages/launch/result'
				})
			}else if(this.orderType == 'activity2'){
				uni.redirectTo({
					url: '/subpages/activity/result'
				})
			}else{
				uni.redirectTo({
					url: '/subpages/pay/result'
				})
			}
		}else{
			uni.showToast({
				title:'支付失败~',
				icon:'none'
			})
		}
		//sheep.$router.redirect('/pages/pay/result', {
		//	orderSN: this.orderSN,
		//	payment: this.payment, //重新支付的时候使用
		//	payState: resultType,
		//	orderType: this.orderType,
		//});
	}
	
	
	/*
	 * 获取H5-真实根地址 兼容hash+history模式
	 */
	getRootUrl() {
	  let url = '';
	  //#ifdef H5
	  url = location.origin + '/';
	  if (location.hash !== '') {
	    url += '#/';
	  }
	  //#endif
	  return url;
	}
	
} 